package com.base.commons.log.filter;

import com.base.commons.log.CommonConstant;
import com.base.commons.log.jaeger.JaegerUtils;
import com.base.commons.log.request.ModifyHttpServletRequestWrapper;
import com.base.commons.tools.utils.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author daiguoping
 * @version 1.00
 * @time 2019/12/27 0027
 * @description
 */
public class TraceFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        String user = ((HttpServletRequest)request).getHeader(CommonConstant.TRACE_ID_HEADER);
        String userTemp = user == null ? "" : user;
        System.out.println("user:".concat(userTemp));
        ModifyHttpServletRequestWrapper httpRequest = new ModifyHttpServletRequestWrapper((HttpServletRequest)request);
        String traceId = httpRequest.getHeader(CommonConstant.TRACE_ID_HEADER);
        String tempTraceId = traceId == null ? "":traceId;
        System.out.println("traceId:______".concat(tempTraceId).concat("______"));
        System.out.println(httpRequest.getRequestURI());
        if (StringUtils.isNotEmpty(traceId)) {
            MDC.put(CommonConstant.LOG_TRACE_ID, traceId);
        }else{
            traceId = JaegerUtils.getTraceId();
            MDC.put(CommonConstant.LOG_TRACE_ID, traceId);
            httpRequest.putHeader(CommonConstant.TRACE_ID_HEADER, traceId);
        }
        filterChain.doFilter(httpRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
